Page({
  data: {
    // 主分类标签
    currentTab: 0,
    currentSubTab: 0,
    
    // 搜索和筛选
    searchKeyword: '',
    showSearch: false,
    showFilter: false,
    selectedGrade: '',
    
    // 批量操作相关
    batchMode: false,
    selectedCount: 0,
    
    // 页面状态
    showBackTop: false,
    refreshing: false,
    gradeOptions: [
      { label: '全部', value: '' },
      { label: '一年级', value: '一年级' },
      { label: '二年级', value: '二年级' },
      { label: '三年级', value: '三年级' },
      { label: '四年级', value: '四年级' },
      { label: '五年级', value: '五年级' },
      { label: '六年级', value: '六年级' }
    ],
    
    // 页面状态
    isLoading: false,
    hasMore: true,
    currentPage: 1,
    
    // 收藏内容
    collections: [
      {
        id: 1,
        title: '那一刻，我很幸福',
        preview: '在我的记忆里，有许多工作像蝴蝶般在面前飞舞，但让我最幸福的，还是在那一刻。那一刻，我和妈妈一起滑冰，我摔倒了，妈妈扶起我...',
        grade: '六年级',
        category: '叙事',
        wordCount: 708,
        date: '2023-05-15'
      },
      {
        id: 2,
        title: '让我敬佩的人',
        preview: '一个熟悉的身影，一抹甜甜的微笑，一声亲切的呼唤，她就是我的语文老师。我的语文老师今年40多岁了，一身黑色的衣服，戴着一个白色的包...',
        grade: '五年级',
        category: '写人',
        wordCount: 825,
        date: '2023-05-10'
      }
    ]
  },

  onLoad: function (options) {
    this.loadCollections();
  },

  // 获取收藏列表
  getCollectionList: function () {
    if (this.data.isLoading || !this.data.hasMore) return;
    
    this.setData({
      isLoading: true
    });
    
    // 模拟网络请求
    setTimeout(() => {
      this.setData({
        isLoading: false,
        currentPage: this.data.currentPage + 1,
        hasMore: this.data.currentPage < 3
      });
    }, 500);
  },

  // 返回上一页
  onBack: function() {
    wx.navigateBack();
  },

  // 切换主分类标签
  switchTab: function(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.currentTab === index) return;
    
    this.setData({
      currentTab: index,
      currentSubTab: 0,
      currentPage: 1,
      hasMore: true,
      isLoading: false
    });
    
    this.getCollectionList();
  },
  
  // 切换二级分类标签
  switchSubTab: function(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.currentSubTab === index) return;
    
    this.setData({
      currentSubTab: index,
      currentPage: 1,
      hasMore: true,
      isLoading: false
    });
    
    this.getCollectionList();
  },

  // 点击收藏项
  onItemTap: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/composition/detail/detail?id=${id}&from=collection`
    });
  },

  // 加载更多
  loadMore: function () {
    this.getCollectionList();
  },

  // 滚动到顶部
  scrollToTop: function() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
  },

  // 监听页面滚动
  onPageScroll: function(e) {
    const scrollTop = e.scrollTop;
    const showBackTop = scrollTop > 300;
    
    if (this.data.showBackTop !== showBackTop) {
      this.setData({
        showBackTop
      });
    }
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    this.setData({
      refreshing: true,
      currentPage: 1,
      collections: [],
      hasMore: true
    });
    
    this.loadCollections().then(() => {
      wx.stopPullDownRefresh();
      this.setData({
        refreshing: false
      });
    });
  },

  // 上拉加载更多
  onReachBottom: function() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadCollections();
    }
  },

  // 加载收藏数据
  loadCollections: function() {
    if (this.data.isLoading) return Promise.resolve();
    
    this.setData({
      isLoading: true
    });

    return new Promise((resolve) => {
      // 模拟网络请求
      setTimeout(() => {
        const newCollections = this.generateMockData();
        const allCollections = this.data.currentPage === 1 ? 
          newCollections : [...this.data.collections, ...newCollections];
        
        this.setData({
          collections: allCollections,
          currentPage: this.data.currentPage + 1,
          hasMore: newCollections.length === 10,
          isLoading: false
        });
        
        resolve();
      }, 800);
    });
  },

  // 生成模拟数据
  generateMockData: function() {
    const titles = ['语文作文素材', '英语阅读理解', '数学应用题', '科学实验报告', '历史知识点'];
    const categories = ['语文', '英语', '数学', '科学', '历史'];
    const grades = ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级'];
    
    return Array.from({length: 10}, (_, i) => ({
      id: Date.now() + i,
      title: titles[i % titles.length] + (i + 1),
      category: categories[i % categories.length],
      grade: grades[i % grades.length],
      preview: '这是一个收藏内容的预览文本，展示主要内容摘要...',
      createTime: new Date(Date.now() - i * 86400000).toLocaleDateString(),
      isSelected: false
    }));
  },
  
  // 搜索输入
  onSearchInput: function(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },
  
  // 搜索确认
  onSearch: function(e) {
    this.setData({
      currentPage: 1,
      hasMore: true,
      isLoading: false
    });
    this.getCollectionList();
  },
  
  // 清除搜索
  clearSearch: function() {
    this.setData({
      searchKeyword: '',
      currentPage: 1,
      hasMore: true,
      isLoading: false
    });
    this.getCollectionList();
  },
  
  // 切换搜索栏显示
  toggleSearch: function() {
    this.setData({
      showSearch: !this.data.showSearch
    });
    // 如果关闭搜索栏，清空搜索关键词
    if (!this.data.showSearch && this.data.searchKeyword) {
      this.clearSearch();
    }
  },

  // 切换筛选面板
  toggleFilter: function() {
    this.setData({
      showFilter: !this.data.showFilter
    });
  },

  // 重置筛选条件
  resetFilter: function() {
    this.setData({
      selectedGrade: ''
    });
  },

  // 确认筛选
  confirmFilter: function() {
    this.setData({
      showFilter: false,
      currentPage: 1,
      hasMore: true,
      isLoading: false
    });
    this.getCollectionList();
  },

  // 阻止事件冒泡
  stopPropagation: function() {
    // 空函数，用于阻止事件冒泡
  },

  // 年级筛选
  onGradeFilter: function(e) {
    const value = e.currentTarget.dataset.value;
    this.setData({
      selectedGrade: value,
      currentPage: 1,
      hasMore: true,
      isLoading: false
    });
    this.getCollectionList();
  },

  // 筛选面板点击事件处理
  onFilterPanelTap: function(e) {
    // 在微信小程序中，使用catchtap可以阻止事件冒泡，无需手动调用stopPropagation
    // 如果需要阻止事件冒泡，建议在wxml中使用catchtap而不是bindtap
    console.log('筛选面板被点击');
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    this.setData({
      currentPage: 1,
      hasMore: true,
      refreshing: true
    });
    this.getCollectionList();
    setTimeout(() => {
      this.setData({ refreshing: false });
    }, 1000);
  },

  // 触底加载更多
  onReachBottom: function() {
    if (!this.data.hasMore || this.data.isLoading) return;
    this.loadMore();
  },

  // 页面滚动
  onPageScroll: function(e) {
    const scrollTop = e.detail.scrollTop;
    this.setData({
      showBackTop: scrollTop > 300
    });
  },

  // 批量选择切换
  onToggleSelection: function(e) {
    const index = e.currentTarget.dataset.index;
    const collections = this.data.collections;
    collections[index].selected = !collections[index].selected;
    
    const selectedCount = collections.filter(item => item.selected).length;
    this.setData({
      collections,
      selectedCount
    });
  },

  // 收藏项点击
  onCollectionTap: function(e) {
    if (this.data.batchMode) return;
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`
    });
  },

  // 收藏项长按
  onCollectionLongPress: function(e) {
    if (this.data.batchMode) return;
    this.setData({
      batchMode: true
    });
  },

  // 分享
  onShare: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.showToast({
      title: '分享功能开发中',
      icon: 'none'
    });
  },

  // 取消收藏
  onUncollect: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认取消收藏',
      content: '取消收藏后，该内容将从收藏列表中移除',
      success: (res) => {
        if (res.confirm) {
          // 这里应该调用API取消收藏
          wx.showToast({
            title: '已取消收藏',
            icon: 'success'
          });
          // 重新加载列表
          this.getCollectionList();
        }
      }
    });
  },

  // 清除搜索
  onClearSearch: function() {
    this.clearSearch();
  },

  // 取消批量操作
  onCancelBatch: function() {
    const collections = this.data.collections.map(item => ({
      ...item,
      selected: false
    }));
    this.setData({
      batchMode: false,
      collections,
      selectedCount: 0
    });
  },

  // 批量分享
  onBatchShare: function() {
    const selectedItems = this.data.collections.filter(item => item.selected);
    if (selectedItems.length === 0) {
      wx.showToast({
        title: '请选择要分享的内容',
        icon: 'none'
      });
      return;
    }
    wx.showToast({
      title: '批量分享功能开发中',
      icon: 'none'
    });
  },

  // 批量删除
  onBatchDelete: function() {
    const selectedItems = this.data.collections.filter(item => item.selected);
    if (selectedItems.length === 0) {
      wx.showToast({
        title: '请选择要删除的内容',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedItems.length} 项内容吗？`,
      success: (res) => {
        if (res.confirm) {
          // 这里应该调用API批量删除
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          this.onCancelBatch();
          this.getCollectionList();
        }
      }
    });
  },

  // 返回顶部
  onBackTop: function() {
    // 滚动到顶部的逻辑
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
  }
})